/**
 * 表格组件SSR导出处理
 * 使用Vue SSR渲染表格组件为HTML
 */

import { createSSRExporter } from '@/utils/componentSSRExporter';
import TableComponent from './index.vue';

// 创建基于SSR的导出处理器
export default createSSRExporter(TableComponent, {
  // 自定义脚本生成
  scriptGenerator(component, options = {}) {
    const { id, props = {} } = component;
    const datas = props.datas || {};
    
    // 基础JS，为表格添加交互功能
    let js = `
// 表格 ${id} 初始化脚本
(function() {
  // 获取表格元素
  const tableEl = document.getElementById("${id}");
  if (!tableEl) return;
  
  // 表格数据
  const tableData = ${JSON.stringify(datas.data || [])};
  
  // 分页配置
  const pagination = {
    currentPage: 1,
    pageSize: ${datas.pageSize || 10},
    total: ${(datas.data || []).length}
  };`;
    
    // 处理分页功能
    if (datas.showPagination) {
      js += `
  // 分页处理
  const paginationEl = tableEl.querySelector('.pagination-container .el-pagination');
  if (paginationEl) {
    // 页面大小切换
    const pageSizeSelect = paginationEl.querySelector('.el-pagination__sizes');
    if (pageSizeSelect) {
      pageSizeSelect.addEventListener('change', function(e) {
        pagination.pageSize = parseInt(e.target.value);
        pagination.currentPage = 1;
        updateTableDisplay();
      });
    }
    
    // 页码点击
    const paginationBtns = paginationEl.querySelectorAll('.el-pager li');
    paginationBtns.forEach(btn => {
      btn.addEventListener('click', function() {
        pagination.currentPage = parseInt(btn.textContent);
        updateTableDisplay();
      });
    });
    
    // 上一页/下一页
    const prevBtn = paginationEl.querySelector('.btn-prev');
    if (prevBtn) {
      prevBtn.addEventListener('click', function() {
        if (pagination.currentPage > 1) {
          pagination.currentPage--;
          updateTableDisplay();
        }
      });
    }
    
    const nextBtn = paginationEl.querySelector('.btn-next');
    if (nextBtn) {
      nextBtn.addEventListener('click', function() {
        const totalPages = Math.ceil(pagination.total / pagination.pageSize);
        if (pagination.currentPage < totalPages) {
          pagination.currentPage++;
          updateTableDisplay();
        }
      });
    }
  }`;
    }
    
    // 处理排序功能
    js += `
  // 表格排序功能
  const sortableHeaders = tableEl.querySelectorAll('.el-table__header th.is-sortable');
  sortableHeaders.forEach(header => {
    header.addEventListener('click', function() {
      const property = this.getAttribute('data-column-id');
      let order = this.getAttribute('aria-sort') || 'ascending';
      order = order === 'ascending' ? 'descending' : 'ascending';
      
      // 清除其他列的排序状态
      sortableHeaders.forEach(h => h.setAttribute('aria-sort', ''));
      
      // 设置当前列的排序状态
      this.setAttribute('aria-sort', order);
      
      // 排序数据
      tableData.sort((a, b) => {
        const aValue = a[property];
        const bValue = b[property];
        
        if (order === 'ascending') {
          return aValue > bValue ? 1 : -1;
        } else {
          return aValue < bValue ? 1 : -1;
        }
      });
      
      // 更新表格显示
      updateTableDisplay();
    });
  });`;
    
    // 处理工具栏按钮
    if (datas.showToolbar) {
      js += `
  // 工具栏功能
  const refreshBtn = tableEl.querySelector('.table-toolbar-buttons .el-button[title="刷新"]');
  if (refreshBtn) {
    refreshBtn.addEventListener('click', function() {
      // 模拟刷新
      const loadingEl = document.createElement('div');
      loadingEl.className = 'el-loading-mask';
      loadingEl.innerHTML = '<div class="el-loading-spinner"><svg class="circular" viewBox="25 25 50 50"><circle class="path" cx="50" cy="50" r="20" fill="none"/></svg></div>';
      tableEl.appendChild(loadingEl);
      
      setTimeout(() => {
        tableEl.removeChild(loadingEl);
      }, 800);
    });
  }`;
    }
    
    // 处理操作按钮
    if (datas.showOperationColumn) {
      js += `
  // 操作按钮功能
  const actionButtons = tableEl.querySelectorAll('.el-table__body .el-button');
  actionButtons.forEach(btn => {
    btn.addEventListener('click', function(e) {
      e.stopPropagation();
      const row = this.closest('tr');
      const rowIndex = Array.from(row.parentNode.children).indexOf(row);
      const rowData = tableData[rowIndex];
      const action = this.textContent.trim();
      
      console.log(\`点击了【\${action}】按钮, 行数据:\`, rowData);
      
      // 添加交互提示
      const notification = document.createElement('div');
      notification.className = 'el-notification right';
      notification.innerHTML = \`
        <div class="el-notification__group">
          <h2 class="el-notification__title">操作提示</h2>
          <div class="el-notification__content">已点击【\${action}】按钮</div>
        </div>
      \`;
      document.body.appendChild(notification);
      
      setTimeout(() => {
        notification.style.opacity = '0';
        setTimeout(() => document.body.removeChild(notification), 300);
      }, 2000);
    });
  });`;
    }
    
    // 处理行点击
    if (datas.highlightCurrentRow) {
      js += `
  // 行点击高亮
  const tableRows = tableEl.querySelectorAll('.el-table__body tr');
  tableRows.forEach(row => {
    row.addEventListener('click', function() {
      // 移除其他行的高亮
      tableRows.forEach(r => r.classList.remove('current-row'));
      // 添加当前行高亮
      this.classList.add('current-row');
    });
  });`;
    }
    
    // 封闭函数
    js += `
  // 更新表格显示的辅助函数
  function updateTableDisplay() {
    // 这里可以添加表格数据更新逻辑
    console.log('表格状态更新:', pagination);
  }
})();`;
    
    return js;
  },
  
  // 自定义CSS生成
  cssGenerator(component, options = {}) {
    const { id, props = {} } = component;
    const datas = props.datas || {};
    
    return `
/* 表格 ${id} 的自定义样式 */
#${id} {
  position: relative;
  width: 100%;
}

#${id} .table-component {
  display: flex;
  flex-direction: column;
}

#${id} .table-overlay {
  display: none; /* 在导出时不显示覆盖层 */
}

#${id} .table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
}

#${id} .pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  margin-top: 10px;
}

/* 为导出优化的表格样式 */
#${id} .el-table {
  border-collapse: collapse;
  width: 100%;
}

#${id} .el-table th,
#${id} .el-table td {
  padding: 12px;
  ${datas.border ? 'border: 1px solid #ebeef5;' : ''}
}

#${id} .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  user-select: none;
}

#${id} .el-table__body tr:nth-child(odd) {
  ${datas.stripe ? 'background-color: #fafafa;' : ''}
}

#${id} .el-table__body tr:hover {
  background-color: #f5f7fa;
}

#${id} .el-table__body tr.current-row {
  background-color: #ecf5ff;
}

/* 按钮样式 */
#${id} .el-button--text {
  padding: 0;
  margin: 0 5px;
}

#${id} .el-button--text.el-button--primary {
  color: #409eff;
}

#${id} .el-button--text.el-button--success {
  color: #67c23a;
}

#${id} .el-button--text.el-button--danger {
  color: #f56c6c;
}

/* 分页器样式 */
#${id} .el-pagination {
  font-weight: normal;
  color: #606266;
  display: flex;
  align-items: center;
}

#${id} .el-pagination button {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  margin: 0 5px;
}

#${id} .el-pagination .el-pager {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

#${id} .el-pagination .el-pager li {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  margin: 0 5px;
}

#${id} .el-pagination .el-pager li.active {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}`;
  },
  
  // 导出所需的资源
  resources: [
    { type: 'css', path: './element-ui.css' }, // Element UI样式
  ]
}); 